package com.hskn.hss.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis连接池
 *
 * @author hskn
 * @email h@iaiot.com
 */
@Slf4j
@Component
public class JedisPoolUtils {

    private static JedisPool jedisPool;

    private static String redisHost;
    @Value("${spring.redis.port}")
    private static Integer redisPort;
    @Value("${spring.redis.password}")
    private static String redisPassword;

    @Value("${spring.redis.host}")
    public void setRedisHost(String host) {
        redisHost = host;
    }

    @Value("${spring.redis.password}")
    public void setRedisPassword(String password) {
        redisPassword = password;
    }

    @Value("${spring.redis.port}")
    public void setRedisPort(Integer port) {
        redisPort = port;
    }

    /**
     * 获取一个jedis 对象
     *
     * @return Jedis
     */
    public static Jedis getJedis() {
        Jedis jedis = null;
        try {
            if (jedisPool == null) {
                poolInit();
            }
            //log.info("==activeCount：{},idleCount：{},waitCount：{}", jedisPool.getNumActive(), jedisPool.getNumIdle(), jedisPool.getNumWaiters());
            jedis = jedisPool.getResource();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return jedis;
    }

    /**
     * 在多线程环境同步初始化
     */
    private static synchronized void poolInit() {
        if (jedisPool == null)
            createJedisPool();
    }

    private static void createJedisPool() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(6000);
            config.setMaxIdle(100);
            //表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；单位毫秒
            //小于零:阻塞不确定的时间,  默认-1
            config.setMaxWaitMillis(1000);
            // 创建连接池
            //connectionTimeout 连接超时（默认2000ms）
            //soTimeout 响应超时（默认2000ms）
            jedisPool = new JedisPool(config, redisHost, redisPort, 10 * 1000, redisPassword);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 释放连接
     *
     * @param jedis jedis
     */
    public static void release(Jedis jedis) {
        if (jedis != null)
            jedis.close();
    }
}